package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.DateUtils;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.NumberUtil;
import com.meirengu.webview.dao.KwWxSubscribeDao;
import com.meirengu.webview.model.KwWxSubscribe;
import com.meirengu.webview.service.HhWxSubscribeService;
import com.meirengu.webview.service.KwOperationLogService;
import com.meirengu.webview.service.WxMqService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HhWxSubScribeServiceImpl extends BaseServiceImpl<KwWxSubscribe> implements HhWxSubscribeService {

    @Autowired
    RedisClient redisClient;

    @Autowired
    ProducerBean producer;

    @Autowired
    private WxMqService wxMqService;

    @Autowired
    private KwWxSubscribeDao kwWxSubscribeDao;

    @Autowired
    private KwOperationLogService kwOperationLogService;

    Logger logger = LoggerFactory.getLogger(DiguaWxSubscribeServiceImpl.class);


    @Override
    public void wxAccessToken(String wxId) throws Exception {
        String accessToken = "";
        String key = wxMqService.getAccessTokenKeyByWxAccount(wxId);
        String appid = "";
        String secret = "";
        /**大姐花*/
        if ("gh_ca34fb2663d4".equals(wxId)) {
            appid = "wxebdf10c9f9c3f683";
            secret = "81e3969bd765f220e1573fd318b933fc";
            /**大哥花*/
        } else if ("gh_73502556f538".equals(wxId)) {
            appid = "wx907dd29f68a02201";
            secret = "a302f0f5fd3985261031677e22854a68";
            /**大妈花花*/
        } else if ("gh_a3fc947894a9".equals(wxId)) {
            appid = "wx6bb78d4b7b70cea3";
            secret = "8a166ff4d80be2ed9a7fd40f048d5cd7";
            /**每天有财*/
        } else if ("gh_ef0cf5e9f36a".equals(wxId)) {
            appid = "wxad81a856a26633e9";
            secret = "96c91e8f2e6c8ccb40658a9c799ec2e6";
            /**大豆花*/
        } else if ("gh_8a691ad25e95".equals(wxId)) {
            appid = "wx535831237081f5ab";
            secret = "a40e10419fef9ba55db20c917f4bba29";
            /**大龙花*/
        } else if ("gh_6c8d7afc54aa".equals(wxId)) {
            appid = "wx8d60b700448896d5";
            secret = "68e56d4e273f6ebf7ac6847badd60cad";
            /**小龙花*/
        } else if ("gh_3e09676b9bda".equals(wxId)) {
            appid = "wxac6645f595d0b681";
            secret = "fa056bba415545d37088459db723aed4";
        } else {
            appid = "";
            secret = "";
        }
        HttpUtil.HttpResult hr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
        int code = hr.getStatusCode();
        logger.info("hr:{}" + hr.toString());
        if (code == 200) {
            logger.info("==wxAccessToken http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            accessToken = returnMsg.getString("access_token");
            redisClient.set(key, accessToken);
        } else {
            logger.warn("==HGHUAWXACCESSTOKEN http requesst fail. code:{}, result:{}", code, hr.toString());
        }
    }


    @Override
    public void createMenu(String wxId) throws Exception {
        JSONObject jsonObject = new JSONObject();
        JSONArray button = new JSONArray();
        JSONObject button1 = new JSONObject();//小额借款
        JSONObject button2 = new JSONObject();//大额借款

        button1.put("type", "view");
        button1.put("name", "小额借款");
        button1.put("url", wxMqService.getUrlByWxAccount(wxId) + "#/market");
        button.add(button1);

        button2.put("type", "view");
        button2.put("name", "大额借款");
        button2.put("url", wxMqService.getUrlByWxAccount(wxId));
        button.add(button2);
        jsonObject.put("button", button);


        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + redisClient.get(wxMqService.getAccessTokenKeyByWxAccount(wxId));
        HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
        System.out.println(hr.toString());
    }

    @Override
    public void createMenuDXL(String wxId) throws Exception {
        JSONObject jsonObject = new JSONObject();
        JSONArray button = new JSONArray();
        JSONObject button1 = new JSONObject();//小额借款
        JSONObject button2 = new JSONObject();//大额借款

        button1.put("type", "view");
        button1.put("name", "免费申请");
        button1.put("url", wxMqService.getUrlByWxAccount(wxId) + "#/market");
        button.add(button1);

        button2.put("type", "view");
        button2.put("name", "小额极速");
        button2.put("url", wxMqService.getUrlByWxAccount(wxId) + "#/market");
        button.add(button2);
        jsonObject.put("button", button);


        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + redisClient.get(wxMqService.getAccessTokenKeyByWxAccount(wxId));
        HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
        System.out.println(hr.toString());
    }



    @Override
    public void createMenuJmd() throws Exception {
        JSONObject jsonObject = new JSONObject();
        JSONArray button = new JSONArray();
        JSONObject button1 = new JSONObject();//小额借款
        JSONObject button2 = new JSONObject();//大额借款

        button1.put("type", "view");
        button1.put("name", "小额借款");
        button1.put("url", "https://h5.kawangdai.com/loan/index.html?cid=channel_jmdwx#/market");
        button.add(button1);

        button2.put("type", "view");
        button2.put("name", "大额借款");
        button2.put("url", "http://www.chaohanjinrong.com/?cid=mtyc");
        button.add(button2);
        jsonObject.put("button", button);


        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + redisClient.get(wxMqService.getAccessTokenKeyByWxAccount("gh_8a691ad25e95"));
        HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
        System.out.println(hr.toString());
    }

    public String getUserList(String openId, String wxId) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + redisClient.get(wxMqService.getAccessTokenKeyByWxAccount(wxId));
        if (StringUtils.isNotBlank(openId)) {
            url = url + "&next_openid=" + openId;
        }
        /*String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=14_XtlAFIKufRItmgnngj9qi00aSvVEgANRktePBLaPct5jQ0okZpNY4IvZN5AQ1LqasQAeITrFAbKOp4upvySBq7KMbz8ETIhAOovNTY4YLPfSn3UWYkPR6cmXkbD822v0fnSuWsGQzt5nrO9aTSNbAEALKF";*/
        HttpUtil.HttpResult hr = HttpUtil.doGet(url);
        int code = hr.getStatusCode();
        String nextOpenId = "";
        if (code == 200) {
            logger.info("==getUserList http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            JSONObject data = returnMsg.getJSONObject("data");
            JSONArray openidAry = data.getJSONArray("openid");
            nextOpenId = returnMsg.getString("next_openid");
            String openid = null;
            //校验是否已订阅
            Map<String, Object> params = new HashMap<>();
            Integer count = null;
            KwWxSubscribe kwWxSubscribe = null;
            for (int i = 0; i < openidAry.size(); i++) {
                openid = openidAry.getString(i);
                params.put("fromUserName", openid);
                params.put("toUserName", wxId);
                count = kwWxSubscribeDao.getCount(params);
                //已有推送记录
                if (!NumberUtil.isNullOrZero(count)) {
                    System.out.println("已有订阅");
                    continue;
                }
                kwWxSubscribe = new KwWxSubscribe();
                kwWxSubscribe.setToUserName(wxId);
                kwWxSubscribe.setFromUserName(openid);
                kwWxSubscribe.setCreateTime(new Date());
                kwWxSubscribe.setMsgType("event");
                kwWxSubscribe.setEvent("subscribe");
                /*logger.info("nikeName:{}" + nikeName);
                kwWxSubscribe.setNikeName(nikeName);*/
                kwWxSubscribeDao.insert(kwWxSubscribe);
            }
        } else {
            logger.warn("==HGHUAWXACCESSTOKEN http requesst fail. code:{}, result:{}", code, hr.toString());
        }
        return nextOpenId;
    }

    @Override
    public void sendTemplateMsg(String name, String wxId, String templateId) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> map = new HashMap<>();
        map.put("toUserName", wxId);
        List<Map<String, Object>> userList = getList(map);
        String openid = null;
        JSONObject dataJson = null;
        JSONObject first = null;
        JSONObject keyword1 = null;
        JSONObject keyword2 = null;
        JSONObject keyword3 = null;
        JSONObject keyword4 = null;
        JSONObject keyword5 = null;
        JSONObject remark = null;
        kwOperationLogService.addOperationLog("2", "sendTemplateMsg", "发送" + wxId + "模板消息",
                name, sdf.format(new Date()), sdf.format(new Date()), "sendTemplateMsg", 0,
                null, null, null);
        for (Map<String, Object> userMap : userList) {
            openid = userMap.get("fromUserName").toString();
            jsonObject.put("touser", openid);
            jsonObject.put("template_id", templateId);
            jsonObject.put("url", wxMqService.getUrlByWxAccount(wxId) + "#/market");
            dataJson = new JSONObject();

            first = new JSONObject();
            first.put("value", name + "-额度高 秒下款");
            first.put("color", "#173177");
            dataJson.put("first", first);

            keyword1 = new JSONObject();
            keyword1.put("value", name);
            keyword1.put("color", "#FF0000");
            dataJson.put("keyword1", keyword1);

            keyword2 = new JSONObject();
            keyword2.put("value", DateUtils.getPrintDate());
            keyword2.put("color", "#173177");
            dataJson.put("keyword2", keyword2);

            /*keyword3 = new JSONObject();
            keyword3.put("value", "7-30天");
            keyword3.put("color", "#173177");
            dataJson.put("keyword3", keyword3);*/

            String platname = wxMqService.getNameByWxAccount(wxId);

            remark = new JSONObject();
            StringBuilder contentBuffer = new StringBuilder();
            contentBuffer.append("您已通过" + platname + "平台获得VIP优先审核，请点击查看详情>>>");
            String contentStr = contentBuffer.toString();
            remark.put("value", contentStr);
            remark.put("color", "#FF0000");
            dataJson.put("remark", remark);

            jsonObject.put("data", dataJson);

            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + redisClient.get(wxMqService.getAccessTokenKeyByWxAccount(wxId));
            HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
            System.out.println(hr.toString());
        }

    }
}
